﻿using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Data;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

namespace IntegrationAgent
{
    public class ERPWebService
    {
        #region 完工信息
        /// <summary>
        /// 完工信息
        /// </summary>
        /// <param name="para"></param>
        /// <param name="dtMaterial"></param>
        /// <param name="strMessage"></param>
        /// <returns></returns>
        public Boolean SendFinishInfo(Dictionary<string, string> para, DataTable dtMaterial, out string strMessage)
        {
            //基本信息
            Dictionary<string, string> child = new Dictionary<string, string>();
            Dictionary<string, object> pBase = new Dictionary<string, object>();
            //pBase.Add("number", para["number"]);                    //单据编码
            pBase.Add("mesBillNo", para["mesBillNo"]);              //MES完工单号
            pBase.Add("mesBillId", para["mesBillId"]);              //MES完工单ID
            pBase.Add("bizDate", para["bizDate"]);                  //日期

            child = new Dictionary<string, string>();
            child.Add("name", para["adminOrgUnit"]);
            pBase.Add("adminOrgUnit", child);        //生产部门

            child = new Dictionary<string, string>();
            child.Add("number", para["productionOrder"]);
            pBase.Add("productionOrder", child);  //生产订单号

            child = new Dictionary<string, string>();
            child.Add("number", para["material"].ToString());
            pBase.Add("material", child);//物料编码

            pBase.Add("operationNo", para["operationNo"]);          //工序号

            child = new Dictionary<string, string>();
            child.Add("number", para["project"]);
            pBase.Add("project", child);                  //项目号

            //pBase.Add("trackNo", para["trackNo"]);                  //跟踪号
            //pBase.Add("classGroup", para["classGroup"]);            //班组

            //物料列表
            List<Dictionary<string, object>> entrys = new List<Dictionary<string, object>>();

            int i = 1;
            foreach (DataRow row in dtMaterial.Rows)
            {
                Dictionary<string, object> item = new Dictionary<string, object>();
                //item.Add("id", string.Empty);//分录ID
                item.Add("seq", i.ToString());//分录序号
                item.Add("reportQty", row["reportQty"].ToString());//汇报数量

                child = new Dictionary<string, string>();
                child.Add("number", row["ProductName"].ToString());
                item.Add("material", child);//物料编码

                item.Add("qty", row["HGQty"].ToString());//合格数量
                item.Add("prodScrapQty", row["GFQty"].ToString());//不合格数量/工废数量
                item.Add("matScrapQty", row["LFQty"].ToString());//料废数量
                item.Add("startDate", row["startDate"].ToString());//实际开始日期
                item.Add("endDate", row["endDate"].ToString());//实际结束日期

                entrys.Add(item);

                i++;
            }

            pBase.Add("entrys", entrys);

            Dictionary<string, object> p = new Dictionary<string, object>();
            p.Add("authCode", "EEC6B4FDF0DDE521315ED9B995FDBC585E377C7A3B11CA7A7C111475C76D6E87");
            p.Add("bizObjectType", "DFBE5164");
            p.Add("operation", "add");
            p.Add("data", pBase);

            ERPWS.WSMesBizOperationFacadeSrvProxyService erpws = new ERPWS.WSMesBizOperationFacadeSrvProxyService();
            string pJson = JsonConvert.SerializeObject(p);
            string strResult = erpws.bizOperation(pJson);

            Object obj = JsonConvert.DeserializeObject(strResult);
            JObject js = obj as JObject;

            string returnCode = js["returnCode"].ToString();

            string returnMsg = string.Empty;

            try
            {
                returnMsg = js["returnMsg"].ToString();
            }
            catch
            {
                //returnMsg = "领料申请发送成功";
            }

            strMessage = returnMsg;

            if (returnCode == "0000")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 退料申请
        /// <summary>
        /// 退料申请
        /// </summary>
        /// <param name="para"></param>
        /// <param name="dtMaterial"></param>
        /// <param name="strMessage"></param>
        /// <returns></returns>
        public Boolean SendTLInfo(Dictionary<string, string> para, DataTable dtMaterial, out string strMessage)
        {
            //基本信息
            Dictionary<string, string> child = new Dictionary<string, string>();
            Dictionary<string, object> pBase = new Dictionary<string, object>();
            //pBase.Add("number", para["number"]);                            //单据编码
            pBase.Add("mesBillNo", para["mesBillNo"]);                      //MES退料单号
            pBase.Add("mesBillId", para["mesBillId"]);                      //MES退料单ID
            pBase.Add("bizDate", para["bizDate"]);                          //日期

            child = new Dictionary<string, string>();
            child.Add("number", para["productionOrderId"]);
            pBase.Add("productionOrderId", child);      //生产订单号

            child = new Dictionary<string, string>();
            child.Add("name", para["adminOrgUnit"]);
            pBase.Add("adminOrgUnit", child);                //部门

            //pBase.Add("description", string.Empty);                  //摘要
            //pBase.Add("billStatus", "已审核");                    //单据状态：已审核
            //pBase.Add("sourceBillType", "退料");            //源单类型：退料
            
            //物料列表
            List<Dictionary<string, object>> entrys = new List<Dictionary<string, object>>();

            int i = 1;
            foreach (DataRow row in dtMaterial.Rows)
            {
                Dictionary<string, object> item = new Dictionary<string, object>();
                //item.Add("id", string.Empty);//分录ID
                item.Add("seq", i.ToString());//分录序号
                item.Add("sourceBillId", para["mesBillId"].ToString());//源单内码
                //item.Add("reqType", row["reqType"].ToString());//类型：料废、工废、合格

                child = new Dictionary<string, string>();
                child.Add("number", row["ProductName"].ToString());
                item.Add("material", child);//物料编码

                //child = new Dictionary<string, string>();
                //child.Add("name", row["Uom"].ToString());
                //item.Add("unit", child);//计量单位

                item.Add("qty", row["Qty"].ToString());//申请数量
                //item.Add("scrapQty", row["scrapQty"].ToString());//报废数量
                //item.Add("issueStorageOrgUnit", string.Empty);//发货库存组织
                //item.Add("reqDate", string.Empty);//需求日期
                //item.Add("operationNo", string.Empty);//工序号
                //item.Add("returnWarehouse", string.Empty);//退料仓库

                entrys.Add(item);

                i++;
            }

            pBase.Add("entrys", entrys);

            Dictionary<string, object> p = new Dictionary<string, object>();
            p.Add("authCode", "EEC6B4FDF0DDE521315ED9B995FDBC585E377C7A3B11CA7A7C111475C76D6E87");
            p.Add("bizObjectType", "7606B3CD");
            p.Add("operation", "add");
            p.Add("data", pBase);
            
            ERPWS.WSMesBizOperationFacadeSrvProxyService erpws = new ERPWS.WSMesBizOperationFacadeSrvProxyService();
            string pJson = JsonConvert.SerializeObject(p);
            string strResult = erpws.bizOperation(pJson);

            Object obj = JsonConvert.DeserializeObject(strResult);
            JObject js = obj as JObject;

            string returnCode = js["returnCode"].ToString();

            string returnMsg = string.Empty;

            try
            {
                returnMsg = js["returnMsg"].ToString();
            }
            catch
            {
                //returnMsg = "领料申请发送成功";
            }

            strMessage = returnMsg;

            if (returnCode == "0000")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 领料申请/补料申请
        /// <summary>
        /// 领料申请/补料申请
        /// </summary>
        /// <param name="para"></param>
        /// <param name="dtMaterial"></param>
        /// <param name="strMessage"></param>
        /// <returns></returns>
        public Boolean SendMaterialAppInfo(Dictionary<string, string> para, DataTable dtMaterial, out string strMessage)
        {
            //基本信息
            Dictionary<string, string> child = new Dictionary<string, string>();
            Dictionary<string, object> pBase = new Dictionary<string, object>();
            //pBase.Add("number", "");            //单据编码
            pBase.Add("mesReqNo", para["mesReqNo"]);        //MES申请单号
            pBase.Add("mesReqId", para["mesReqId"]);        //MES申请单ID
            pBase.Add("bizDate", para["bizDate"]);          //日期

            child = new Dictionary<string, string>();
            child.Add("name", para["reqOrgUnit"]);
            pBase.Add("reqOrgUnit", child);    //分厂

            child = new Dictionary<string, string>();
            child.Add("number", para["applier"]);
            pBase.Add("applier", child);          //申请人

            //pBase.Add("costCenter", "");    //成本中心
            //pBase.Add("description", "");  //摘要

            child = new Dictionary<string, string>();
            child.Add("name", para["workOrder"]);
            pBase.Add("workOrder", child);      //工作令号

            pBase.Add("billStatus", "已审核");    //单据状态：已审核

            //物料列表
            List<Dictionary<string, object>> entrys = new List<Dictionary<string, object>>();
            
            int i = 1;
            foreach (DataRow row in dtMaterial.Rows)
            {
                Dictionary<string, object> item = new Dictionary<string, object>();
                //item.Add("id", string.Empty);//分录ID
                item.Add("seq", i.ToString());//分录序号

                child = new Dictionary<string, string>();
                child.Add("number", row["ProductName"].ToString());
                item.Add("material", child);//物料编码

                //child = new Dictionary<string, string>();
                //child.Add("name", row["Uom"].ToString());
                //item.Add("unit", child);//计量单位

                item.Add("qty", row["Qty"].ToString());//申请数量
                //item.Add("approvedQty", string.Empty);//核准数量
                //item.Add("issueStorageOrgUnit", string.Empty);//发货库存组织

                child = new Dictionary<string, string>();
                child.Add("number", row["MfgOrderName"].ToString());
                item.Add("productionOrder", child);//生产订单号

                //item.Add("classGroup", string.Empty);//班组
                //item.Add("issuedQty", string.Empty);//已发料数量

                entrys.Add(item);

                i++;
            }

            pBase.Add("entrys", entrys);

            Dictionary<string, object> p = new Dictionary<string, object>();
            p.Add("authCode", "EEC6B4FDF0DDE521315ED9B995FDBC585E377C7A3B11CA7A7C111475C76D6E87");
            p.Add("bizObjectType", "BFBCAD51");
            p.Add("operation", "add");
            p.Add("data", pBase);
            
            ERPWS.WSMesBizOperationFacadeSrvProxyService erpws = new ERPWS.WSMesBizOperationFacadeSrvProxyService();
            string pJson = JsonConvert.SerializeObject(p);
            string strResult = erpws.bizOperation(pJson);

            Object obj = JsonConvert.DeserializeObject(strResult);
            JObject js = obj as JObject;

            string returnCode = js["returnCode"].ToString();

            string returnMsg = string.Empty;

            try
            {
                returnMsg = js["returnMsg"].ToString();
            }
            catch
            {
                //returnMsg = "领料申请发送成功";
            }
            
            strMessage = returnMsg;

            if (returnCode == "0000")
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        #endregion

        #region 物料库存查询
        /// <summary>
        /// 物料库存查询
        /// </summary>
        /// <param name="para"></param>
        /// <param name="strMessage"></param>
        /// <returns></returns>
        public DataTable GetMaterialInfo(Dictionary<string, string> para, out string strMessage)
        {
            StringBuilder filters = new StringBuilder();
            filters.Append(string.Format("material.number LIKE '%{0}%'", para["material"]));
            if (para.ContainsKey("warehouse"))
            {
                filters.Append(string.Format("AND warehouse.name LIKE '%{0}%'", para["warehouse"]));

            }
            if (para.ContainsKey("MaterialName")) {
                filters.Append(string.Format(" and material.name LIKE '%{0}%'", para["MaterialName"]));
            }
            //filters.Append(string.Format("AND lot LIKE '%{0}%'", para["lot"]));
            //filters.Append(string.Format("AND project LIKE '%{0}%'", para["project"]));

            Dictionary<string, string> p = new Dictionary<string, string>();
            p.Add("authCode", "EEC6B4FDF0DDE521315ED9B995FDBC585E377C7A3B11CA7A7C111475C76D6E87");
            p.Add("bizObjectType", "BA8AD747");
            p.Add("filters", filters.ToString());
            p.Add("sorters", "material.number,warehouse.name");

            ERPWS.WSMesBizOperationFacadeSrvProxyService erpws = new ERPWS.WSMesBizOperationFacadeSrvProxyService();
            string pJson = JsonConvert.SerializeObject(p);
            string strResult = erpws.queryData(pJson);

            Object obj = JsonConvert.DeserializeObject(strResult);
            JObject js = obj as JObject;

            string returnCode = js["returnCode"].ToString();

            string returnMsg = string.Empty;

            try
            {
                returnMsg = js["returnMsg"].ToString();
            }
            catch
            {
                //returnMsg = "领料申请发送成功";
            }

            strMessage = returnMsg;

            if (returnCode == "0000")
            {

                string dataSize = js["dataSize"].ToString();
                JArray jarray = (JArray)js["data"];

                DataTable DT = new DataTable();
                DT.Columns.Add("material");         //物料编码
                DT.Columns.Add("materialname");         //物料名称
                DT.Columns.Add("storageOrgUnit");   //库存组织
                DT.Columns.Add("storageOrgUnitname");   //库存组织名称
                DT.Columns.Add("companyOrgUnit");   //公司
                DT.Columns.Add("companyOrgUnitname");   //公司名称
                DT.Columns.Add("warehouse");        //仓库
                DT.Columns.Add("warehousename");        //仓库名称
                //DT.Columns.Add("lot");              //批次号
                DT.Columns.Add("unit");             //计量单位
                DT.Columns.Add("unitname");             //计量单位名称
                DT.Columns.Add("baseQty");          //基本数量
                DT.Columns.Add("lockQty");          //锁库数量
                //DT.Columns.Add("trackNumber");      //跟踪号
                //DT.Columns.Add("project");          //项目号
                 DT.Columns.Add("model");          //材料规格型号

                for (int i = 0; i < jarray.Count; i++)
                {
                    string data = jarray[i].ToString();
                    Object obj1 = JsonConvert.DeserializeObject(data);
                    JObject js1 = obj1 as JObject;

                    DataRow row = DT.NewRow();

                    row["material"] = js1["material"]["number"].ToString();
                    row["materialname"] = js1["material"]["name"].ToString();
                    row["model"] = js1["material"]["model"].ToString();
                    row["storageOrgUnit"] = js1["storageOrgUnit"]["number"].ToString();
                    row["storageOrgUnitname"] = js1["storageOrgUnit"]["name"].ToString();
                    row["companyOrgUnit"] = js1["companyOrgUnit"]["number"].ToString();
                    row["companyOrgUnitname"] = js1["companyOrgUnit"]["name"].ToString();
                    row["warehouse"] = js1["warehouse"]["number"].ToString();
                    row["warehousename"] = js1["warehouse"]["name"].ToString();
                    //row["lot"] = js1["lot"].ToString();
                    row["unit"] = js1["unit"]["number"].ToString();
                    row["unitname"] = js1["unit"]["name"].ToString();
                    row["baseQty"] = js1["baseQty"].ToString();
                    row["lockQty"] = js1["lockQty"].ToString();
                    //row["trackNumber"] = js1["trackNumber"].ToString();
                    //row["project"] = js1["project"].ToString();
                    DT.Rows.Add(row);
                }

                return DT;
            }
            else
            {
                return null;
            }
        }
        #endregion

        #region 注销
        /// <summary>
        /// 注销
        /// </summary>
        /// <returns></returns>
        public Boolean Logout()
        {
            //EASLogin.EASLoginProxyService eas = new EASLogin.EASLoginProxyService();
            //eas.logout("user", "Eas111111", "T001", "l2");
            return true;
        }
        #endregion

        #region 登录
        /// <summary>
        /// 登录
        /// </summary>
        /// <returns></returns>
        public Boolean Login()
        {
            EASLogin.EASLoginProxyService eas = new EASLogin.EASLoginProxyService();
            EASLogin.WSContext context = eas.login("daijie", "Eas111111", "eas", "T001", "l2", 1);
            return true;
        }
        #endregion
    }
}
